#!/usr/bin/env python
# -*- coding:utf-8 -*-
from typing import List

from LfreeObj import LfreeObj

from conn.MyLogs import MyLogs


# ***
# * 这个工具类主要处理数据表中针对dataL!这个固定标准表数据的读取与判断
# * Auth: tuut
# ***
class ExcelDictUtil:
    SUCCESS = 200

    def __init__(self, conn):
        self.conn = conn
        return

    @staticmethod
    def loadDataL(x, Y):
        return 0

    # **
    # Params:
    #  std 判定依据参考值
    #  area 数据区域
    #  target 数据获取坐标
    def VLOOKUP(self, std, area, target):
        return 0

    # **
    # 年期 单一计算单元年数
    # 供款期 判定基础数据来源
    def vlookup_by_year_and_anb_and_payment_term(self, args: List[str]):
        year = args[0]
        anb = args[1]
        payment_term = args[2]
        list_flg = False
        cal_year = []
        if isinstance(year, list) or isinstance(year, range) or isinstance(year, tuple):
            list_flg = True
            cal_year = [str(i) for i in year]
        else:
            if year == 0:
                return {"code": 200, "data": 0}
        cal_anb_index = ExcelDictUtil.get_anb_index(anb)
        area_table = LfreeObj.PAYMENT_TERM[payment_term]
        try:
            # 1 数据查询 -----------------------------------------------------------------------------------
            fetch_sql = f"SELECT val FROM {area_table} %s"
            where_sql = f' WHERE 1=1'
            where_sql = where_sql + f' AND anb_index = {cal_anb_index}'
            if list_flg:
                where_sql = where_sql + f' AND anb in ({",".join(cal_year)})'
            else:
                where_sql = where_sql + f' AND anb = {year}'
            data_list = self.conn.sql_fetch(fetch_sql % where_sql)
            if len(data_list) > 0:
                return {"code": 200, "data": list([i[0] for i in data_list])}
            return {"code": 400, "data": None}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    # **
    # 年期 单一计算单元年数
    # 供款期 判定基础数据来源
    def vlookup_gcv_by_year_and_anb_and_payment_term(self, args: List[str]):
        year = args[0]
        anb = args[1]
        payment_term = args[2]
        list_flg = False
        cal_year = []
        if isinstance(year, list) or isinstance(year, range) or isinstance(year, tuple):
            list_flg = True
            cal_year = [str(i) for i in year]
        else:
            if year == 0:
                return {"code": 200, "data": 0}
        cal_anb_index = ExcelDictUtil.get_anb_index(anb)
        area_table = LfreeObj.GCV_PAYMENT_TERM[payment_term]
        try:
            # 1 数据查询 -----------------------------------------------------------------------------------
            fetch_sql = f"SELECT val FROM {area_table} %s"
            where_sql = f' WHERE 1=1'
            where_sql = where_sql + f' AND anb_index = {cal_anb_index}'
            if list_flg:
                where_sql = where_sql + f' AND anb in ({",".join(cal_year)})'
            else:
                where_sql = where_sql + f' AND anb = {year}'
            data_list = self.conn.sql_fetch(fetch_sql % where_sql)
            if len(data_list) > 0:
                return {"code": 200, "data": list([i[0] for i in data_list])}
            return {"code": 400, "data": None}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    @staticmethod
    def spow(n, m):
        res = 1
        for i in range(m):
            res *= n
        return res

    def get_anb_index(anb):
        try:
            DATA_ANB_INDEX = binary_search(LfreeObj.ANB_CASE, anb)
            if DATA_ANB_INDEX[0] <= 0:
                _res = LfreeObj.ANB_CASE[0]
            else:
                if DATA_ANB_INDEX[1]:
                    _res = LfreeObj.ANB_CASE[DATA_ANB_INDEX[0] - 1]
                else:
                    _res = LfreeObj.ANB_CASE[DATA_ANB_INDEX[0]]
            return _res
        except Exception as e:
            print(e)


def binary_search(arr, target):
    res = 0
    left = 0
    chg_flg = False
    right = len(arr) - 1
    try:
        if arr.index(target) > 0:
            res = arr.index(target)
            return [res, chg_flg]
    except ValueError as e:
        print("not in list..continue split check")

    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            res = mid
            return [res, chg_flg]
        elif arr[mid] < target:
            left = mid + 1
            res = left
            chg_flg = True
        else:
            right = mid - 1
            res = right
            chg_flg = True
        if mid == 1:
            return [res, chg_flg]
    return [res, chg_flg]


if __name__ == '__main__':
    print("1111111111111111")
